package net.xprogrammer.booclipse.generator.toc.parser.daisy.model;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

/**
 * daisy中toc最主要的项，就是左边目录中的书签，可包含多个下级
 * 
 * @author gyzhang
 * @date 2012-4-2 上午11:56:09
 * @version 3.0
 */
@XStreamAlias("navPoint")
public class NavPoint {

	@XStreamAsAttribute()
	private String			id;
	@XStreamAsAttribute()
	private String			playOrder;
	private NavLabel		navLabel;
	private Content			content;

	private List<NavPoint>	navPoints	= new ArrayList<NavPoint>();

	public NavPoint() {

	}

	public NavPoint(NavLabel navLabel, Content content) {
		super();
		this.navLabel = navLabel;
		this.content = content;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPlayOrder() {
		return playOrder;
	}

	public void setPlayOrder(String playOrder) {
		this.playOrder = playOrder;
	}

	public NavLabel getNavLabel() {
		return navLabel;
	}

	public void setNavLabel(NavLabel navLabel) {
		this.navLabel = navLabel;
	}

	public Content getContent() {
		return content;
	}

	public void setContent(Content content) {
		this.content = content;
	}

	public List<NavPoint> getNavPoints() {
		return navPoints;
	}

	public void setNavPoints(List<NavPoint> navPoints) {
		this.navPoints = navPoints;
	}

	public void print() {
		System.out.println("navPoint label: " + getNavLabel().getText());
		System.out.println("navPoint content: " + getContent().getSrc());

		for (NavPoint navPoint : navPoints) {
			if (null != navPoint)
				navPoint.print();
		}
	}

	/**
	 * 递归写入eclipse的toc书签
	 * 
	 * @param navPoint
	 *            一个toc，可能含有下级toc
	 * @param hrefPrefix
	 *            eclipse中存放toc中html文件的目录
	 * @param fileWriter
	 *            文件写入器
	 * @param level
	 *            缩进层级，用来将子toc向右缩进
	 * @throws IOException
	 */

	public void write2Booclipse(NavPoint navPoint, String hrefPrefix, FileWriter fileWriter, int level) throws IOException {
		if (null != navPoint) {
			String label = navPoint.getNavLabel().getText();
			String href = hrefPrefix + navPoint.getContent().getSrc();

			String brk = "\r\n";//回车换行

			String indentation = StringUtils.repeat(" ", 2 * level);//缩进的空格

			fileWriter.write(indentation + "<topic href=\"" + href + "\" label=\"" + label + "\">" + brk);//写入一个toc书签

			level++;//下一级，加1
			List<NavPoint> subNavPoints = navPoint.getNavPoints();//获取下级toc书签
			if (null != subNavPoints) {
				for (NavPoint subNavPoint : subNavPoints) {
					subNavPoint.write2Booclipse(subNavPoint, hrefPrefix, fileWriter, level);//递归写入下级toc书签
				}
			}

			fileWriter.write(indentation + "</topic>" + brk);//写入toc书签的结束行

		}
	}

}
